<template>
  <div class="container" @click="lockStatus=''">
    <div style="display: flex;height:52px;align-items: center">
      <Button type="primary" @click="toSafeValidate">安全校验配置</Button>
      <div class="lock">
        <img @click.stop="lockClick('lock')" :style="{opacity:lockStatus==='lock'? 0.5 : 1}"
             src="../../../../assets/img/userControl/3.png"
             height="31" width="30"/>
        <div style="width:20px"></div>
        <img @click.stop="lockClick('open')" :style="{opacity:lockStatus ==='open'? 0.5 : 1}"
             src="../../../../assets/img/userControl/1.png"
             height="31" width="38"/>
        <!--<div class="temperature">23℃</div>-->
      </div>
    </div>
    <div class="decription">
      <div class="img-box">
        <template v-for="(item,index) in lockArr">
          <!--透明框，承载点击事件-->
          <Poptip placement="right" :style="{top:item.top+'px',left:item.left+'px'}">
            <div :key="index+'box'"
                 :id="'poptipDiv'+index"
                 :style="{width:'31px',height:'31px',opacity:0,
                 cursor:item.isControl==='1'?'pointer':'auto'}"
            ></div>
            <div class="api" slot="content">
              <template v-if="item.isControl>0 && item.opTime">
                此设备已预置，不可操作
              </template>
              <template v-else-if="item.isControl==1 && item.isCheck==1 && !item.opTime">
                <div>
                  <Button @click="buttonClick(0,index)" class="button-open" style="margin: 0 10px 0 0" size="small">打开
                  </Button>
                  <Button @click="buttonClick(1,index)" class="button-lock" size="small">关闭</Button>
                </div>
              </template>
              <template v-else-if="item.isControl==1 && item.isCheck==0 && !item.opTime">
                <div style="margin-bottom:10px;">
                  <Button @click="buttonClick(2,index)" class="button-open" size="small" style="margin: 0 10px 0 0">打开
                  </Button>
                  <Button @click="buttonClick(3,index)" class="button-lock" size="small">关闭</Button>
                </div>
                <div>
                  <Button @click="buttonClick(4,index)" class="button-setting" type="primary" size="small">预置打开</Button>
                  <Button @click="buttonClick(5,index)" class="button-setting" type="primary" size="small">预置关闭</Button>
                </div>
              </template>
              <template v-else-if="item.isControl==2 && item.isCheck==0 && !item.opTime">

                <Button class="button-setting" style="margin-left:20px"
                        @click="buttonClick(6,index)"
                        type="primary" size="small">设置
                </Button>
                <Button class="button-setting"
                        @click="buttonClick(7,index)"
                        type="primary" size="small">预置设置
                </Button>
              </template>
              <template v-else-if="item.isControl==2 && item.isCheck==1 && !item.opTime">

                <Button class="button-setting" style="margin-left:20px"
                        @click="buttonClick(8,index)"
                        type="primary" size="small">设置
                </Button>
              </template>
              <template v-else>
                此设备不可用
              </template>
            </div>
          </Poptip>

        </template>
        <template v-for="(img,index) in lockArr">
          <img v-if="img.isControl>0 && (!img.notLock || lockStatus)" :key="index"
               :style="{top:img.top+'px',left:img.left+'px',
               opacity:img.isControl>0 && !img.notLock?1:0,
               cursor:img.isControl>0 && !img.notLock?'pointer':'auto'}"
               src="../../../../assets/img/userControl/3.png"
               @click.stop="lockItemClick(index)"
               height="31" width="30"/>
        </template>
        <!--<div class="details-info">-->
          <!--<div>瞬时流量：<span>0m/h</span></div>-->
          <!--<div>累计流量：<span>0m/h</span></div>-->
        <!--</div>-->
      </div>
    </div>
    <!--安全校验-->
    <Modal v-model="safeCheckShow"
           @on-ok="safeButtonClick"
           class-name="vertical-center-modal"
           :mask-closable="false"
           width="40"
           :loading="modelLoading"
           scrollable center title="安全校验">
      <div>
        <Form
                ref="safeModel"
                :model="safeForm"
                :rules="safeValidate"
                label-position="right" :label-width="110">
          <Row :gutter="20">
            <Col span="24">
              <div class="form-type"><img src="../../../../assets/img/userControl/9.png" height="14" width="12"/>安全确认
              </div>
            </Col>
            <Col span="12">
              <FormItem label="操作账号" prop="serial">
                <Input size="small" v-model="safeForm.serial"></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="账号密码" prop="password">
                <Input type="password" size="small" v-model="safeForm.password"></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem size="small" label="受控设备名称">
                <Input :disabled="true" v-model="safeForm.deviceName"></Input>
              </FormItem>
            </Col>

            <Col span="24">
              <div class="form-type"><img src="../../../../assets/img/userControl/9.png" height="14" width="12"/>双人监护
              </div>
            </Col>
            <Col span="12">
              <FormItem label="监护账号" prop="tutelageAccount">
                <Input size="small" v-model="safeForm.tutelageAccount"></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="监护账号密码" prop="tutelagePassword">
                <Input type="password" size="small" v-model="safeForm.tutelagePassword"></Input>
              </FormItem>
            </Col>

            <Col span="24">
              <div class="form-type"><img src="../../../../assets/img/userControl/9.png" height="14" width="12"/>
                控制预置信息
              </div>
            </Col>
            <Col span="12">
              <FormItem label="控制预置状态">
                <Input size="small" :disabled="true" v-model="safeForm.initialStatus"></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="预置操作">
                <Input :disabled="true" size="small" v-model="safeForm.initialAction"></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="预置账号">
                <Input :disabled="true" size="small" v-model="safeForm.initialAccount"></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="执行时间" prop="actionTime">
                <DatePicker type="datetime"
                            v-model="safeForm.actionTime"
                            format="yyyy-MM-dd HH:mm:ss"
                            size="small"
                            :options="optionsDate"
                            @on-change="dateTimeChange2"
                            placeholder="请设置预置执行时间"
                >
                </DatePicker>
              </FormItem>
            </Col>
            <Col span="12" v-if="dataType==4">
              <FormItem label="数值设置" prop="number">
                <Input type="number" size="small" v-model="safeForm.number"></Input>
              </FormItem>
            </Col>

          </Row>

        </Form>
      </div>
    </Modal>

    <!--预置控制设置-->
    <Modal v-model="initialSettingShow"
           :loading="modelLoading"
           @on-ok="initialButtonClick"
           class-name="vertical-center-modal"
           :mask-closable="false"
           scrollable center :title="dataType==2?'预置控制设置':dataType==3? '设置':'预置设置'">
      <div>
        <Form
                :model="initialSettingForm"
                :rules="initialSettingRuleValidate"
                ref="initialSettingFormValidate"
                label-position="right" :label-width="110">
          <Row :gutter="0">
            <Col span="12">
              <FormItem label="设备名称" prop="name">
                <Input :disabled="true" size="small" v-model="initialSettingForm.name"></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="操作" prop="action">
                <Input :disabled="true" size="small" v-model="initialSettingForm.action"></Input>
              </FormItem>
            </Col>
            <Col span="12" v-if="dataType==4 || dataType==3">
              <FormItem label="数值设置" prop="number">
                <Input type="number" size="small" v-model="initialSettingForm.number"></Input>
              </FormItem>
            </Col>
            <Col span="24" v-if="dataType!=3">
              <FormItem label="预置执行时间" prop="time">
                <DatePicker type="datetime"
                            v-model="initialSettingForm.time"
                            format="yyyy-MM-dd HH:mm:ss"
                            size="small"
                            :options="optionsDate"
                            @on-change="dateTimeChange"
                            placeholder="请设置预置执行时间"
                >
                </DatePicker>
              </FormItem>
            </Col>

          </Row>

        </Form>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
    selectUserOperationControl,
    safetyVerificationOperation,
    controlSurfaceOperation
} from '@/api/scada'
import moment from 'moment'

export default {
    name: "singleControl",
    props: {},
    data() {
        return {
            clickTop: 0,
            tabDisabled:false,
            clickLeft: 0,
            opValue: '',
            dataType: '',
            settingBox: false,
            poptipShow: false,
            deviceSettingType: 1,
            description: {},
            lockStatus: '',
            lockArr: [
                {
                    top: 50,
                    left: 68,
                    equipName: '热量器1'
                },
                {
                    top: 25,
                    left: 250,
                    equipName: '压力表1'
                },
                {
                    top: 25,
                    left: 313,
                    equipName: '温度表1'
                },
                {
                    top: 25,
                    left: 471,
                    equipName: '压力表2'
                },
                {
                    top: 25,
                    left: 615,
                    equipName: '温度表2'
                },
                {
                    top: 50,
                    left: 992,
                    equipName: '热量器2'
                },
                //第二排
                {
                    top: 127,
                    left: 68,
                    equipName: '电动调节阀1'
                },
                {
                    top: 102,
                    left: 380,
                    equipName: '1线换热器'
                },
                {
                    top: 136,
                    left: 628,
                    equipName: '循环泵1'
                },
                {
                    top: 87,
                    left: 875,
                    equipName: '压力表3'
                },
                {
                    top: 87,
                    left: 935,
                    equipName: '温度表3'
                },
                //第三排
                {
                    top: 218,
                    left: 138,
                    equipName: '压力表4'
                },
                {
                    top: 184,
                    left: 472,
                    equipName: '压力表5'
                },
                {
                    top: 184,
                    left: 615,
                    equipName: '温度表4'
                },
                {
                    top: 210,
                    left: 993,
                    equipName: '热量器3'
                },
                //第四排

                {
                    top: 275,
                    left: 136,
                    equipName: '温度表5'
                },
                {
                    top: 265,
                    left: 380,
                    equipName: '2线换热器'
                },
                {
                    top: 300,
                    left: 628,
                    equipName: '循环泵2'
                },
                {
                    top: 247,
                    left: 875,
                    equipName: '压力表6'
                },
                {
                    top: 247,
                    left: 935,
                    equipName: '温度表6'
                },
                //第五排
                {
                    top: 413,
                    left: 157,
                    equipName: '显示器1'
                },
                {
                    top: 413,
                    left: 290,
                    equipName: '电动调节阀2'
                },
                {
                    top: 385,
                    left: 732,
                    equipName: '补水泵1'
                },
                {
                    top: 356,
                    left: 803,
                    equipName: '显示器2'
                },
                //第六排
                {
                    top: 525,
                    left: 60,
                    equipName: '自流井'
                },
                {
                    top: 510,
                    left: 157,
                    equipName: '显示器3'
                },
                {
                    top: 510,
                    left: 488,
                    equipName: '水箱'
                },
                {
                    top: 485,
                    left: 732,
                    equipName: '补水泵2'
                },
                {
                    top: 456,
                    left: 803,
                    equipName: '显示器4'
                },
                //第七排
                {
                    top: 564,
                    left: 130,
                    equipName: '深水泵'
                },
                {
                    top: 573,
                    left: 875,
                    equipName: '集水坑'
                },
                {
                    top: 593,
                    left: 1032,
                    equipName: '排水泵'
                },
            ],
            safeCheckShow: false,
            settingShow: false,
            initialSettingShow: false,
            modelLoading: true,
            optionsDate: {
                disabledDate(date) {
                    return date && date.valueOf() < Date.now() - 86400000 + 10 * 60 * 1000;
                }
            },
            currentDevice: {},

            safeForm: {
                serial: '',
                password: '',
                deviceName: '',
                tutelageAccount: '',
                tutelagePassword: '',
                initialStatus: '未预置',
                initialAction: '',
                initialAccount: JSON.parse(localStorage.getItem('admin')).sys.user["4"].user.info.sub,
                number: 0,
                actionTime: '',
            },
            safeValidate: {
                password: [
                    {required: true, message: '请输入账号密码', trigger: 'blur'}
                ],
                serial: [
                    {required: true, message: '请输入操作账号', trigger: 'blur'}
                ],
                tutelageAccount: [
                    {required: true, message: '监护账号', trigger: 'blur'}
                ],
                tutelagePassword: [
                    {required: true, message: '监护账号密码', trigger: 'blur'}
                ],
                number: [
                    {required: true, message: '设置数值', trigger: 'blur'},
                    {type: 'string', message: '请设置一个整数', pattern: /^[1-9]+[0-9]*$/,trigger: 'blur'},
                ],
                actionTime: [
                    {required: true, message: '设置执行时间', trigger: 'blur', pattern: /.+/},
                    {validator:function (rule,value,callback) {
                            let diff = new Date(value)-new Date();
                            if(diff<60*1000) {
                                callback(new Error('设置时间必须大于当前时间1分钟以上'))
                            } else {
                                callback()
                            }
                            console.log(diff)
                        },trigger:'change'}
                ],
            },
            settingForm: {
                name: '',
                action: '0',
                number: 123,
            },
            settingRuleValidate: {
                number: [
                    {required: true, message: '请设置数值', trigger: 'blur'}
                ]
            },
            initialSettingForm: {
                name: '',
                number: 0,
                action: '',
                time: '',
            },
            initialSettingRuleValidate: {
                number: [
                    {required: true, message: '请设置数值', trigger: 'blur'},
                    {type: 'string', message: '请设置一个整数', pattern: /^[1-9]+[0-9]*$/,trigger: 'blur'},
                ],
                time: [
                    {required: true, message: '请设置执行时间', trigger: 'blur', pattern: /.+/},
                    {validator:function (rule,value,callback) {
                        let diff = new Date(value)-new Date();
                        if(diff<60*1000) {
                            callback(new Error('设置时间必须大于当前时间1分钟以上'))
                        } else {
                            callback()
                        }
                        console.log(diff)
                        },trigger:'change'}
                ],
            },
            controlBasicInfo: {}
        };
    },
    computed: {},
    created() {
    },
    mounted() {
    	console.log('mounted')
        this.controlBasicInfo = JSON.parse(sessionStorage.getItem('controlBasicInfo')) || {}
        const {siteId, custId} = this.controlBasicInfo
        let data = {
            "siteId": siteId,
            "custId": custId
        }
        selectUserOperationControl(data).then(res => {
            const {code, result = []} = res;
            if (code === 200 && Array.isArray(result)) {
                result.forEach(item => {
                    this.lockArr.forEach(lockItem => {
                        if (lockItem.equipName === item.equipName) {
                            for (let name in item) {
                                lockItem[name] = item[name];
                            }
                            this.$set(lockItem, 'lockStatus', true);
                        }
                    })
                })
            }
        })

    },
    watch: {},
    methods: {
        safetyControl() {

            let userInfo = JSON.parse(sessionStorage.getItem('controlBasicInfo'))
            let data = {
                dataType: this.dataType,
                custId: userInfo.custId,
                stId: userInfo.siteId,
                devId: this.currentDevice.equipId,
                devType: this.currentDevice.equipType,
                opValue: this.opValue,
                opuserAccount: this.safeForm.serial,
                opuserAccountPwd: this.safeForm.password,
                guauserAccount: this.safeForm.tutelageAccount,
                guauserAccountPwd: this.safeForm.tutelagePassword,
                opTime: this.safeForm.actionTime
            }
            if (this.dataType == 4) {
                data.opValue = this.safeForm.number;
            }
            safetyVerificationOperation(data).then(res => {
                const {code, result, message} = res;
                if (code != 200) {
                    this.$Message.error(message)
                } else {
                    this.$Message.success(message)
                }
            }).finally(() => {
                this.safeForm.serial = ''
                this.safeForm.password = ''
                this.safeForm.tutelageAccount = ''
                this.safeForm.tutelagePassword = ''
                this.safeForm.actionTime = ''
                this.safeForm.number = 0
            })
        },
        generalControl() {
            let userInfo = JSON.parse(sessionStorage.getItem('controlBasicInfo'))
            let data = {
                dataType: this.dataType,
                custId: userInfo.custId,
                stId: userInfo.siteId,
                devId: this.currentDevice.equipId,
                devType: this.currentDevice.equipType,
                opValue: this.opValue,
            }
            if (this.dataType == 2 || this.dataType == 4) {
                data.opTime = this.initialSettingForm.time;
            }
            if (this.dataType == 3 || this.dataType == 4) {
                data.opValue = this.initialSettingForm.number
            }
            controlSurfaceOperation(data).then(res => {
                const {code, result, message} = res;
                if (code != 200) {
                    this.$Message.error(message)
                } else {
                    this.$Message.success(message)
                }
            }).finally(()=>{
                this.initialSettingForm.time = ''
                this.initialSettingForm.number = 0
            })
        },
        lockItemClick(i) {
            let me = this;
            if (this.lockStatus) {
                let content = ''
                if (this.lockStatus === 'lock') {
                    content = '<p>是否上锁</p>'
                } else if (this.lockStatus === 'open') {
                    content = '<p>是否解锁</p>'
                }
                this.$Modal.confirm({
                    title: '提示',
                    content: content,
                    onOk: () => {
                        if (me.lockStatus === 'lock') {
                            me.lockArr[i].notLock = false;
                        } else if (me.lockStatus === 'open') {
                            me.lockArr[i].notLock = true;
                        }
                        me.lockStatus = '';
                    },
                    onCancle: () => {
                        me.lockStatus = '';
                    }
                });
            }
        },

        toSafeValidate() {
            this.$router.push({path: '/scada/userControl/validateConfig'})
        },
        dateTimeChange2(e) {
            this.safeForm.actionTime = e;
        },
        dateTimeChange(e) {
            this.initialSettingForm.time = e;
        },
        buttonClick(type, index) {
            let me = this;
            this.currentDevice = this.lockArr[index]
            switch (type) {
                case 0:
                    this.safeCheckShow = true;
                    this.opValue = 1
                    this.dataType = '2'
                    this.safeForm.initialAction = '打开'
                    this.safeForm.deviceName = this.lockArr[index].equipName
                    break;
                case 1:
                    this.safeCheckShow = true;
                    this.opValue = 0;
                    this.dataType = '2'
                    this.safeForm.initialAction = '关闭'
                    this.safeForm.deviceName = this.lockArr[index].equipName
                    break;
                case 2:
                    this.opValue = '1';
                    this.dataType = ''
                    this.$Modal.confirm({
                        title: '打开确认',
                        content: '确定执行控制吗？',
                        onOk: () => {
                            me.generalControl()
                        },
                        onCancle: () => {
                            me.lockStatus = '';
                        }
                    });

                    break;
                case 3:
                    this.opValue = '0'
                    this.dataType = '1'
                    this.$Modal.confirm({
                        title: '关闭确认',
                        content: '确定执行控制吗？',
                        onOk: () => {
                            me.generalControl()
                        },
                        onCancle: () => {
                            me.lockStatus = '';
                        }
                    });
                    break;
                case 4:
                    this.opValue = '1'
                    this.initialSettingForm.name = this.lockArr[index].equipName;
                    this.initialSettingForm.action = '打开';
                    this.dataType = '2'
                    this.initialSettingShow = true;
                    break;
                case 5:
                    this.opValue = '0'
                    this.initialSettingForm.name = this.lockArr[index].equipName;
                    this.initialSettingForm.action = '关闭';
                    this.dataType = '2'
                    this.initialSettingShow = true;
                    break;
                case 6:
                    this.initialSettingForm.name = this.lockArr[index].equipName;
                    this.initialSettingForm.action = '置数';
                    this.dataType = '3'
                    this.initialSettingShow = true;
                    break;
                case 7:
                    this.initialSettingForm.name = this.lockArr[index].equipName;
                    this.initialSettingForm.action = '置数';
                    this.dataType = '4'
                    this.initialSettingShow = true;
                    break;
                case 8:
                    this.safeCheckShow = true;
                    this.dataType = '4'
                    this.safeForm.initialAction = '置数'
                    this.safeForm.deviceName = this.lockArr[index].equipName
                    break;
                default:
                    break;
            }
        },
        initialButtonClick() {
            this.$refs['initialSettingFormValidate'].validate((valid) => {
                if (valid) {
                    this.initialSettingShow = false;
                    this.generalControl()
                } else {
                    this.modelLoading = false;
                    setTimeout(() => {
                        this.modelLoading = true;
                    })

                }
            })
        },
        safeButtonClick() {
            this.$refs['safeModel'].validate((valid) => {
                if (valid) {
                    this.safeCheckShow = false;
                    this.safetyControl()
                } else {
                    this.modelLoading = false;
                    setTimeout(() => {
                        this.modelLoading = true;
                    })

                }
            })
        },
        lockClick(type) {
            this.lockStatus = type
        }
    },
    components: {}
};
</script>

<style lang="scss" scoped>
  .form-type {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    color: #008df0;
    font-size: 14px;
    > img {
      margin-right: 2px;
    }
  }

  ::v-deep .vertical-center-modal {
    display: flex;
    align-items: center;
    justify-content: center;

    .ivu-modal {
      top: 0;
    }
  }

  .container {
    width: 100%;
    height: 100%;
    padding: 0 20px;
  }

  .decription {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    .img-box {
      height: 659px;
      width: 1113px;
      position: relative;
      background: url("../../../../assets/img/photoVoltaic/1.gif") no-repeat center / cover;
      > img, > div {
        position: absolute;
      }
      .button-open {
        background: #92D66E;
        border-color: #92D66E;
        color: white;
        font-size: 12px !important;
        height: 30px;
        margin-left: 10px;
      }
      .button-lock {
        background: #FC807E;
        border-color: #FC807E;
        color: white;
        font-size: 12px !important;
        height: 30px;
      }
      .button-setting {
        height: 30px;
        font-size: 12px
      }

      .device-type-1 {
        display: flex;
        justify-content: space-around;
        align-items: center;
        width: 137px;
        height: 62px;
        background: url("../../../../assets/img/userControl/11.png") no-repeat center / cover;
      }
      .device-type-3 {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 152px;
        height: 62px;
        background: url("../../../../assets/img/userControl/11.png") no-repeat center / cover;
      }
      .device-type-2 {
        width: 161px;
        height: 109px;
        background: url("../../../../assets/img/userControl/12.png") no-repeat center / cover;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        > div {
          padding: 20px;
          height: 40%;
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: flex-start;
        }
      }
      .device-position-1 {
        top: 50px;
        left: 68px
      }
      .device-position-2 {
        top: 136px;
        left: 628px;
      }
      .device-position-3 {
        top: 300px;
        left: 628px;
      }

      .details-info {
        background: #f7f7f7;
        color: #666666;
        padding: 5px 10px;
        span {
          color: #57a3f3;
        }
      }
    }
  }

  .lock {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    width: 259px;
    height: 52px;
    background: url("../../../../assets/img/userControl/8.png") no-repeat center / cover;
    .temperature {
      position: absolute;
      right: 35px;
      height: 52px;
      line-height: 52px;
      color: #0893fd;
    }
  }
</style>
